package com.yixun.service.impl;

import com.alibaba.fastjson.JSON;
import com.yixun.entity.YxOperate;
import com.yixun.entity.YxUser;
import com.yixun.mapper.OptMapper;
import com.yixun.service.LogSetService;
import com.yixun.service.OptService;
import com.yixun.service.RedisService;
import com.yixun.util.LogUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class OptServiceImpl implements OptService {

    private final OptMapper optMapper;

    private final LogSetService logSetService;

    private final RedisService redisService;

    public OptServiceImpl(OptMapper optMapper, LogSetService logSetService, RedisService redisService) {
        this.optMapper = optMapper;
        this.logSetService = logSetService;
        this.redisService = redisService;
    }

    @Override
    public String getOperateTree(String optId) {
        List<YxOperate> operateList = optMapper.getOperateAllList();
        YxOperate operate = optMapper.getOperateBean(optId);
        if (null != operate) {
            String json_str = "[{\"id\":" + operate.getOpt_id() + ",\"text\":\""
                             + operate.getOpt_name() + "\",\"attributes\":{\"opt_code\":\""+operate.getOpt_code()+"\"}";
            String child_str = getAllOperateTreeHandl(operateList,getChildOperateListByID(operateList,operate.getOpt_id()+""));
            if (null != child_str && !"".equals(child_str)) {
                json_str += ",\"children\":[" + child_str + "]";
            }
            json_str += "}]";
            return json_str;
        } else {
            return "[]";
        }
    }

    @Override
    public List<YxOperate> getChildOptList(String optId) {
        List<YxOperate> operateList = optMapper.getOperateAllList();
        List<YxOperate> child_opt_list = new ArrayList<>();
        for (YxOperate opt: operateList) {
            if (optId.equals(opt.getParent_id() + "")) {
                child_opt_list.add(opt);
            }
        }
        return child_opt_list;
    }

    @Override
    @Transactional
    public int insertOpt(YxUser sessionUser, YxOperate operate) {
        int row;
        YxOperate parentOpt = optMapper.getOperateBean(operate.getParent_id() + "");
        Long opt_id = redisService.incr("opt_id", 1L);
        operate.setOpt_id(opt_id);
        operate.setTree_position(parentOpt.getTree_position() + opt_id + "$");
        row = optMapper.insertOpt(operate);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.ADD, "权限", JSON.toJSONString(operate), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    public YxOperate getOperateBean(String opt_id) {
        return optMapper.getOperateBean(opt_id);
    }

    @Override
    @Transactional
    public int updateOpt(YxUser sessionUser, YxOperate operate) {
        int row;
        row = optMapper.updateOpt(operate);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.UPDATE,"权限", JSON.toJSONString(operate), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int delOpt(YxUser sessionUser,String id) {
        int row = 0;
        String[] ids = id.split(",");
        for (String opt_id: ids) {
            String tree_position = optMapper.getTreePositionByOptId(opt_id);
            optMapper.delOptAndChild(tree_position);
            row++;
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.DELETE,"权限", JSON.toJSONString(id), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int moveOpt(YxUser sessionUser, String parent_id, String opt_ids) {
        int row = 0;
        String parent_tree_position = optMapper.getTreePositionByOptId(parent_id);
        if (null != opt_ids && !"".equals(opt_ids)) {
            String[] ids = opt_ids.split(",");
            for (String id : ids) {
                moveOperateHandle(id, parent_id, parent_tree_position);
                row++;
            }
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.MOVE,"权限", JSON.toJSONString(parent_id + "--" + opt_ids), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int sortOpt(YxUser sessionUser, String ids) {
        int row = 0;
        String[] opt_ids = ids.split(",");
        Map<String,String> m = new HashMap<>();
        for (int i = 0; i < opt_ids.length; i++) {
            m.put("opt_id", opt_ids[i]);
            m.put("opt_sort", (i+1) + "");
            optMapper.sortOpt(m);
            row++;
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.SAVE_SORT,"权限", JSON.toJSONString(ids), sessionUser);
            return row;
        }
        return row;
    }

    /*=======================================moveOperateHandle===============================================*/

    public void moveOperateHandle(String opt_id, String parent_id, String parent_tree_position){
        String tree_position = parent_tree_position + opt_id + "$";
        Map<String,String> map =  new HashMap<>();
        map.put("opt_id", opt_id);
        map.put("parent_id", parent_id);
        map.put("tree_position",tree_position);

        if (optMapper.moveOpt(map) > 0) {
            // 该节点下的子节点一并转移
            List<YxOperate> child_list = getChildOptList(opt_id);
            if (null != child_list && child_list.size() > 0) {
                for (YxOperate child: child_list) {
                    moveOperateHandle(child.getOpt_id() + "", opt_id, tree_position);
                }
            }
        }
    }

    /*=======================================moveOperateHandle===============================================*/


    /*=======================================OPT_Tree_Util===============================================*/
    public List<YxOperate> getChildOperateListByID(List<YxOperate> operateList,String opt_id){
        List<YxOperate> child_opt_list = new ArrayList<>();
        for (YxOperate opt: operateList) {
            if (opt_id.equals(opt.getParent_id() + "")) {
                child_opt_list.add(opt);
            }
        }
        return child_opt_list;
    }

    public String getAllOperateTreeHandl(List<YxOperate> operateList,List<YxOperate> dl){
        String json_str = "";
        String show_status;
        if (null != dl && dl.size() > 0) {
            for (YxOperate opt: dl) {
                show_status ="";
                json_str += ",{";
                json_str += "\"id\":" + opt.getOpt_id() + ","
                        + "\"text\":\"" + opt.getOpt_name()
                        + "\",\"attributes\":{\"opt_code\":\""+opt.getOpt_code()+"\"}";
                List<YxOperate> child_d_list = getChildOperateListByID(operateList,opt.getOpt_id()+ "");
                if (null != child_d_list && child_d_list.size() > 0) {
                    json_str += show_status;
                    json_str +=",\"children\":["+ getAllOperateTreeHandl(operateList,child_d_list) + "]";
                }
                json_str += "}";
            }
            if (!"".equals(json_str)) {
                json_str = json_str.substring(1);
            }
        }
        return json_str;
    }
    /*=======================================OPT_Tree_Util===============================================*/






}
